package com.zhiqian.rpc;

import com.zhiqian.bean.RpcRequest;
import com.zhiqian.bean.RpcResponse;
import com.zhiqian.service.ServiceProvider;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

@Slf4j
public class RequestHandlerThread implements Runnable {
    private Socket socket;
    private RequestHandler requestHadnler;
    private ServiceProvider serviceRegistry;

    public RequestHandlerThread(Socket socket, RequestHandler requestHandler, ServiceProvider serviceRegistry){
        this.socket=socket;
        this.requestHadnler=requestHandler;
        this.serviceRegistry=serviceRegistry;
    }

    @Override
    public void run() {
        try(ObjectInputStream objectInputStream=new ObjectInputStream(socket.getInputStream());
            ObjectOutputStream objectOutputStream=new ObjectOutputStream(socket.getOutputStream())){
            RpcRequest rpcRequest=(RpcRequest)objectInputStream.readObject();
            String interfaceName = rpcRequest.getInterfaceName();
            Object service = serviceRegistry.getService(interfaceName);
            Object result=requestHadnler.handle(rpcRequest,service);
            objectOutputStream.writeObject(RpcResponse.success(result));
            objectOutputStream.flush();
        }catch (IOException | ClassNotFoundException e){
            log.info("调用时有错误发生：{}",e);
        }
    }
}
